<template>
  <div class="login-container">
      <!--其他登录方式对话框-->  
      <el-dialog title="其他登录方式" :visible.sync="showDialog">
        <social-sign />
      </el-dialog>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" autocomplete="on" label-position="left">
      <!--登录界面实现-->  
      <el-row :gutter="20" type="flex" class="row-bg" justify="center">
      <!-- 登录介绍页 -->
      <el-col :span="7" class="login-intro">
      <el-card shadow="hover" class="intro-card">
        <h1 class="intro-title">欢迎使用SAU实习管理系统</h1>
        <p class="intro-text">项目详细功能实现介绍：</p>
        <el-divider />
        <el-descriptions :column="1" border>
          <el-descriptions-item label="系统功能">
            <el-tag type="info">学生信息管理</el-tag>
            <el-tag type="info">系部信息管理</el-tag>
            <el-tag type="info">教师信息管理</el-tag>
            <el-tag type="info">生产实践管理</el-tag>
            <el-tag type="info">顶岗实践管理</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      </el-col>
  
      <!-- 登录表单 -->
      <el-col :span="12">
        <el-card shadow="always" class="login-card">
          <div class="login-header">
            <el-divider content-position="center" class="custom-divider"></el-divider>
             <div class="login-prompt">
              <h2 class="login-title">登录您的账号</h2>
              <p class="login-subtitle">请输入您的用户名和密码以继续</p>
             </div>
          </div>
  
          <el-form-item prop="username">
              <el-input 
                ref="username"
                v-model="loginForm.username"
                placeholder="Username"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </el-form-item>
          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="password">
              <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="Password"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              
            </el-form-item>
          </el-tooltip>  
            <el-form-item>
              <div class="captcha-container">
                <el-input
                  v-model="inputVal"
                  placeholder="请输入验证码"
                  class="captcha-input"
                />
                <validate-code ref="ref_validateCode" @change="changeCode" />
              </div>
            </el-form-item>
  
            <el-form-item>
              <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
            </el-form-item>
  
            <el-form-item>
              <el-button 
               :loading="loading" type="primary" 
               @click.native.prevent="compare();handleLogin()"
              >
                立即登录
              </el-button>
              <el-button class="thirdparty-button" type="primary" @click="showDialog=true">
              其他登录方式  
              </el-button>
            </el-form-item>
        </el-card>
      </el-col>
      </el-row>
    </el-form>
  
    <div class="footer">
      <span>@2025 SAU实习管理系统</span>
    </div>
    </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import SocialSign from './components/SocialSignin'
import ValidateCode from '@/components/LoginYZM/ValidateCode'
import axios from 'axios'

export default {
  name: 'Login',
  components: { SocialSign, ValidateCode },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: 'admin',
        password: '111111',
        rememberMe: false
      },
      inputVal: "",
      checkCode: "",
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // 检查本地存储中是否有记住的登录信息
    const rememberedUser = localStorage.getItem('rememberedUser')
    if (rememberedUser) {
      try {
        const userData = JSON.parse(rememberedUser)
        this.loginForm.username = userData.username || ''
        this.loginForm.password = userData.password || ''
        this.loginForm.rememberMe = true
      } catch (e) {
        localStorage.removeItem('rememberedUser')
      }
    }
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
    
    // 页面加载完成后添加类名
    setTimeout(() => {
      const divider = document.querySelector('.custom-divider')
      if (divider) {
        divider.classList.add('is-loaded')
      }
    }, 300)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    compare() {
      const isValid = this.inputVal.toUpperCase() === this.checkCode
      if (!isValid) {
        this.$message.error("验证码错误，请重新输入")
        this.inputVal = ""
        this.$refs["ref_validateCode"].draw()
      }
      return isValid
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (!this.compare()) {
            return false
          }

          this.loading = true

          axios.post('http://localhost:8080/api/login', {
            username: this.loginForm.username,
            password: this.loginForm.password
          }, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          .then(response => {
            const res = response.data

            if (res.code === 200) {
              // 如果勾选了"记住我"，保存用户名和密码到本地存储
              if (this.loginForm.rememberMe) {
                localStorage.setItem('rememberedUser', JSON.stringify({
                  username: this.loginForm.username,
                  password: this.loginForm.password
                }))
              } else {
                localStorage.removeItem('rememberedUser')
              }
              
              // 直接跳转到目标页面
              this.$router.push({ 
                path: this.redirect || '/DingGangShiXi', 
                query: this.otherQuery 
              })
            } else {
              this.$message.error(res.message || '登录失败')
            }
          })
          .catch(error => {
            console.error('登录请求失败:', error)
            let errorMessage = '网络异常，请稍后再试'
            
            if (error.response) {
              if (error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message
              } else if (error.response.status === 401) {
                errorMessage = '用户名或密码错误'
              } else if (error.response.status === 500) {
                errorMessage = '服务器内部错误'
              }
            } else if (error.request) {
              errorMessage = '无法连接到服务器，请检查网络'
            }
            
            this.$message.error(errorMessage)
          })
          .finally(() => {
            this.loading = false
          })

        } else {
          console.log('表单验证失败')
          this.$message.error('请输入正确的用户名和密码')
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    changeCode(value) {
      this.checkCode = value
    }
  }
}
</script>

<style lang="scss">
/* 保持原有样式不变 */
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  padding: 40px;
  max-width: 540px;
  margin: 0 auto;
  transition: transform 0.3s ease;

  &:hover {
    transform: scale(1.02);
  }
}

.el-input {
  width: 100%;
  height: 50px;
  font-size: 16px;
  line-height: 50px;

  input {
    height: 50px;
    padding: 0 15px;
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    transition: border-color 0.3s ease;

    &:focus {
      border-color: #409eff;
    }
  }
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  background-image: url('~@/assets/Login_images/Login.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  overflow: hidden;

  .footer {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 14px;
    color: #fff;
  }
}

.row-bg {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  max-width: 1200px;
}

.login-intro {
  width: 100%;
  max-width: 540px;
  margin-right: 20px;
}

.intro-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  transition: transform 0.3s ease;
  padding: 24px;
}

.intro-card:hover {
  transform: scale(1.02);
}

.intro-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.intro-text {
  font-size: 16px;
  color: #555;
  line-height: 1.6;
  margin-bottom: 20px;
  text-align: center;
}

.el-descriptions {
  font-size: 16px;
  color: #555;
}

.el-descriptions-item__label {
  font-weight: bold;
  color: #333;
}

.el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-tag:nth-child(1) {
  background-color: #f0f9eb;
  color: #67c23a;
  border-color: #e1f3d8;
}
.el-tag:nth-child(2) {
  background-color: #fef0f0;
  color: #f56c6c;
  border-color: #fde2e2;
}
.el-tag:nth-child(3) {
  background-color: #fdf6ec;
  color: #e6a23c;
  border-color: #faecd8;
}
.el-tag:nth-child(4) {
  background-color: #ecf5ff;
  color: #409eff;
  border-color: #d9ecff;
}
.el-tag:nth-child(5) {
  background-color: #f4f4f5;
  color: #909399;
  border-color: #e9e9eb;
}

.el-tag:hover {
  transform: scale(1.1);
  opacity: 0.9;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-input {
  width: 120px;
  margin-right: 8px;
}

.custom-divider {
  margin:0px 0px 50px 0px;

  &::before,
  &::after {
    border-color: #dcdfe6;
    border-width: 1px;
    height: 1px;
  }

  .el-divider__text {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    background-color: transparent;
    padding: 0 24px;
    position: relative;
    z-index: 1;
    opacity: 0;
    transform: translateY(-10px);
    transition: opacity 0.5s ease, transform 0.5s ease;
  }

  &.is-loaded .el-divider__text {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-prompt {
  text-align: center;
  margin-bottom: 20px;
}
.login-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}
.login-subtitle {
  font-size: 14px;
  color: #666;
}
</style>